package com.eqdd.yiqidian.ui.function.shopping

import android.graphics.Color
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.ShoppingProductBean
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonConverter
import com.eqdd.yiqidian.kotlin.imgPathPreview
import com.eqdd.yiqidian.ui.companyspace.ProDemandInfoActivity
import com.eqdd.yiqidian.utils.ImageUtil
import com.lzy.okgo.OkGo
import com.lzy.okrx2.adapter.FlowableBody
import com.shizhefei.mvc.MVCCoolHelper
import io.reactivex.Flowable
import kotlinx.android.synthetic.main.fragment_space.view.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.startActivity
import java.util.*

/**
 * Created by jhj on 18-9-25.
 */
class ShoppingDemandFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_space, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val status = arguments?.getInt(Config.STATUS)
        if (status == 3 || status == 0) {
            var pageNum = 0
            val mvcHelper = MVCCoolHelper<List<ShoppingProductBean>>(view.coolRefreshView)
            val list = arrayListOf<ShoppingProductBean>()
            view.recyclerView.addItemDecoration(DividerLineItemDecoration(activity))
            view.recyclerView.layoutManager = LinearLayoutManager(activity)
            val slimAdapterEx = SlimAdapterEx.create()
                    .register<ShoppingProductBean>(R.layout.list_item_150, SlimInjector<ShoppingProductBean> { data, injector ->
                        data?.let {
                            injector?.text(R.id.tv_content, "【${it.productName}】${it.productType}")
                            // demand(injector, it.productImg?: "", it.productName, it.productPrice, it.demandAddress)
                        }
                    })
                    .attachTo(view.recyclerView)
                    .updateData(list as List<*>?) as SlimAdapterEx<ShoppingProductBean>?

            ItemClickSupport.addTo(view.recyclerView)
                    .setOnItemClickListener { _, position, v ->
                        val bean = slimAdapterEx?.getDataItem(position)
                        activity?.startActivity<ProDemandInfoActivity>(Config.ID to bean?.productId, Config.TYPE to 2, "fun" to 2)
                    }

            val dataSource = ModelRx2DataSource<ShoppingProductBean>(ModelRx2DataSource.OnLoadSource<ShoppingProductBean> { page, register ->
                if (page == 1) {
                    pageNum = 0
                }
                OkGo.post<HttpResult<List<ShoppingProductBean>>>(HttpConfig.BASE_URL + HttpConfig.SHOPPING_DEMAND_NEW)
                        .params("page", pageNum)
                        .converter(object : JsonConverter<HttpResult<List<ShoppingProductBean>>>() {
                            override fun test() {
                                super.test()
                            }
                        })
                        .adapt(FlowableBody<HttpResult<List<ShoppingProductBean>>>())
                        .flatMap({ result ->
                            pageNum = result.page
                            Flowable.just(result.items ?: arrayListOf())
                        })
            })

            mvcHelper.setDataSource(dataSource)
            mvcHelper.adapter = slimAdapterEx
            mvcHelper.refresh()

        } else if (status == 2 || status == 1) {
            var pageNum = 0
            val mvcHelper = MVCCoolHelper<List<ShoppingProductBean>>(view.coolRefreshView)
            val list = arrayListOf<ShoppingProductBean>()
            view.recyclerView.addItemDecoration(DividerLineItemDecoration(activity))
            view.recyclerView.layoutManager = LinearLayoutManager(activity)
            val slimAdapterEx = SlimAdapterEx.create()
                    .register<ShoppingProductBean>(R.layout.list_item_150, SlimInjector<ShoppingProductBean> { data, injector ->
                        data?.let {
                            injector?.text(R.id.tv_content, "【${it.productName}】${it.productType}")
                            //demand(injector, it.productImg, it.productName, it.productPrice, it.productArea)
                        }
                    })
                    .attachTo(view.recyclerView)
                    .updateData(list as List<*>?) as SlimAdapterEx<ShoppingProductBean>?

            ItemClickSupport.addTo(view.recyclerView)
                    .setOnItemClickListener { recyclerView, position, v ->
                        val bean = slimAdapterEx?.getDataItem(position)
                        activity?.startActivity<ProDemandInfoActivity>(Config.ID to bean?.productId, Config.TYPE to 2, "fun" to 2)
                    }

            val dataSource = ModelRx2DataSource<ShoppingProductBean>(ModelRx2DataSource.OnLoadSource<ShoppingProductBean> { page, register ->
                if (page == 1) {
                    pageNum = 0
                }
                OkGo.post<HttpResult<List<ShoppingProductBean>>>(HttpConfig.BASE_URL + HttpConfig.SHOPPING_PRODUCT_DEMAND)
                        .params("page", pageNum)
                        .params("type", status + 1) //2-推荐，3-热门
                        .converter(object : JsonConverter<HttpResult<List<ShoppingProductBean>>>() {
                            override fun test() {
                                super.test()
                            }
                        })
                        .adapt(FlowableBody<HttpResult<List<ShoppingProductBean>>>())
                        .flatMap({ result ->
                            pageNum = result.page
                            Flowable.just(result.items ?: arrayListOf())
                        })
            })

            mvcHelper.setDataSource(dataSource)
            mvcHelper.adapter = slimAdapterEx
            mvcHelper.refresh()
        }
    }

    fun demand(injector: IViewInjector<*>?, img: String, name: String, price: Int?, position: String?) {
        val str = String.format(Locale.CHINA, "产品价格：￥%s元", price)
        val span = SpannableString(str)
        span.setSpan(ForegroundColorSpan(Color.RED), 5, str.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        injector
                ?.with<ImageView>(R.id.iv_image) { view ->
                    if (img.isNotBlank()) {
                        view.visibility = View.VISIBLE
                        view.onClick {
                            activity?.imgPathPreview(img)
                        }
                        Glide.with(this)
                                .asBitmap()
                                .apply(ImageUtil.optionsNormal)
                                .load(img)
                                .into(view)
                    } else {
                        view.visibility = View.GONE
                    }
                }
                ?.text(R.id.tv_name, String.format(Locale.CHINA, "需求名称：%s", name))
                ?.text(R.id.tv_post, span)
                ?.text(R.id.tv_msg, String.format(Locale.CHINA, "发货地址：%s", position))
    }

}